import ldap
import sys
import os
import ml

def addProUser(user, project):
    l = ldap.open("localhost", 389)
    l.simple_bind_s("cn=admin,dc=localnet,dc=org", "nordercode")
    p = l.search_s("ou=projects,o="dbsolution sas",dc=localnet,dc=org", ldap.SCOPE_ONELEVEL, "cn="+project)
    if len(p) != 1:
        print "errore ricerca"
        sys.exit(0)
    u = l.search_s("", ldap.SCOPE_SUBTREE, "(&(objectClass=inetOrgPerson)(uid=%s))"%user)
    if len(u) != 1:
        print "errore di ricerca"
        sys.exit(0)
        
    if p[0][1].has_key('memberUid'):
        for us in p[0][1].get('memberUid'):
            if us == user:
                return
    l.modify_s(p[0][0], [(ldap.MOD_ADD, 'memberUid', user)])
    
#    os.symlink('/home/projects/'+project, '/home/'+user+'/projects/'+project)
    os.popen("ldapmanager/apps/core/utility/proanduser createlink %s %s" %(project, user)).read()
        
    ml.addUser(u[0][1]['mail'][0], project)

def delProUser(user, project):
    l = ldap.open("localhost", 389)
    l.simple_bind_s("cn=admin,dc=localnet,dc=org", "nordercode")
    p = l.search_s("ou=projects,o="dbsolution sas",dc=localnet,dc=org", ldap.SCOPE_ONELVEL, "cn="+project)
    if len(p) != 1:
        print "errore ricerca"
        sys.exit(0)
    u = l.search_s("", ldap.SCOPE_SUBTREE, "(&(objectClass=inetOrgPerson)(uid=%s))"%user)
    if len(u) != 1:
        print "errore di ricerca"
        sys.exit(0)
    
    if p[0][1].has_key('memberUid'):
        f = False
        for us in p[0][1].get('memberUid'):
            if us == user:
                f = True
                break
        if not f:
            return
        
    l.modify_s(p[0][0], [(ldap.MOD_DELETE, 'memberUid', user)])    

    #os.unlink('/home/'+user+'/projects/'+project)
    os.popen("ldapmanager/apps/core/utility/proanduser deletelink %s %s" %(project, user)).read()

    ml.delUser(u[0][1]['mail'][0], project)
    
